const path = require('path');
const multer = require('@koa/multer')
const Jimp = require('jimp');
const {UPLOAD_PATH,UPLOAD_PICTURE} =require("../config/path")
// 上传头像中间件
// const uploadAvatar = multer({
//   dest: UPLOAD_PATH,
// })

const uploadAvatar = multer({
  // dest: './uploads'
  storage: multer.diskStorage({
    destination(req, file, callback) {
      callback(null,UPLOAD_PATH )
    },
    filename(req, file, callback) {
      callback(null, file.originalname)
    }
  })
})
// 上传图片
// const uploadPicture=multer({
//   dest:UPLOAD_PICTURE
// })
const uploadPicture = multer({
  // dest: './uploads'
  storage: multer.diskStorage({
    destination(req, file, callback) {
      callback(null,UPLOAD_PICTURE )
    },
    filename(req, file, callback) {
      callback(null, file.originalname)
    }
  })
})
const handleAvatar = uploadAvatar.single("avatar")
const handlePicture = uploadPicture.array('picture', 9)
const pictureResize = async (ctx, next) => {
  try {
    // 1.获取所有的图像信息
    const files=ctx.request.files

    // 2.对图像进行处理(sharp/jimp)
    for (let file of files) {
      const destPath = path.join(file.destination, file.filename);
      console.log(destPath);
      Jimp.read(file.path).then(image => {
        image.resize(1280, Jimp.AUTO).write(`${destPath}-large`);
        image.resize(640, Jimp.AUTO).write(`${destPath}-middle`);
        image.resize(320, Jimp.AUTO).write(`${destPath}-small`);
      });
    }

    await next();
  } catch (error) {
    console.log(error);
  }
}
module.exports = {
    handleAvatar,
    handlePicture,
    pictureResize
}
